package com.xls.boxlibrary.duihuanjibi;


import static com.xls.commonlibrary.constant.Const.MMKV_IS_UPDATE_GAME;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_AD_INIT_SUCCESS;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_LOGIN_DISSMISS_DIALOG;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_TIXIAN_SHOWQUAN_OK;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_WX_INFO_GET_SUCCESS;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_HEADIMGURL;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_NICKNAME;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xls.boxlibrary.Consts.IntentConsts;
import com.xls.boxlibrary.Consts.StateConsts;
import com.xls.boxlibrary.R;
import com.xls.boxlibrary.customcontrol.RatioImageView;
import com.xls.boxlibrary.customcontrol.RoundedImageView;
import com.xls.boxlibrary.customcontrol.StatusBarHeightView;
import com.xls.boxlibrary.dilog.JiFenDialog;
import com.xls.boxlibrary.entity.JiFenMingXiEntity;
import com.xls.boxlibrary.entity.UserEntity;
import com.xls.boxlibrary.mvp.MVPBaseActivity;
import com.xls.boxlibrary.network.RequestCallBack;
import com.xls.boxlibrary.tixianjilu.TiXianJiLuActivity;
import com.xls.boxlibrary.utils.AppUtils;
import com.xls.boxlibrary.utils.TUtils;
import com.xls.commonlibrary.BuildConfig;
import com.xls.commonlibrary.ad.adn.gm.GMFullUtil;
import com.xls.commonlibrary.ad.adn.reward.util.PointUtil;
import com.xls.commonlibrary.ad.adn.reward.util.ShowRewardAdsUtil;
import com.xls.commonlibrary.bean.ShowEcpmResult;
import com.xls.commonlibrary.constant.Const;
import com.xls.commonlibrary.http.box.SPUtils;
import com.xls.commonlibrary.ui.dialog.TimerDialog;
import com.xls.commonlibrary.util.MMKVUtil;
import com.xls.commonlibrary.util.dislogx.DialogXUtil;
import com.xls.commonlibrary.util.eventbus.MessageEvent;
import com.xls.commonlibrary.wxapi.ConstWx;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;

import javax.annotation.Nullable;


/**
 * MVPPlugin
 */

public class DuiHuanJiBiActivity extends MVPBaseActivity<DuiHuanJiBiContract.View, DuiHuanJiBiPresenter> implements DuiHuanJiBiContract.View, View.OnClickListener {
    RatioImageView riv_activity;
    private TextView title_text;
    private ImageView title_back;
    private RoundedImageView youxi_icon;
    private TextView youxi_name;
    private TextView youxi_org;
    private TextView youxi_shouyi_yue_num;
    private RecyclerView duihuanjilu_duihuanguize;
    private TextView duihuanjilu_duihuanguize_btn;
    private RelativeLayout title_rl;
    private StatusBarHeightView title_rl_content;
    private RelativeLayout item_youxi;
    private RelativeLayout duihuanjinbi_youxi;
    private TextView duihuanjinbi_leve;
    private TextView duihuanjinbi_qianshu;
    private RelativeLayout duihuanjinbi_content;
    private TextView duihuanjibi_duihuanguize_hint;
    private RecyclerView duihuanjilu_guize;
    private TextView title_right;
    private LinearLayout duihuanjinbi_guize_rl;
    private RoundedImageView duihuanjinbi_head;
    private TextView duihuanjinbi_nickname;
    private LinearLayout duihuanjilu_shipin_btn;
    private RelativeLayout rl_bg;


    int showCount = 1;// 广告显示计数
    long current = 0;// 三次内累计

    public static void startActivity(Context context, JiFenMingXiEntity jiFenMingXiEntity, String type) {
        Intent intent = new Intent(context, DuiHuanJiBiActivity.class);
        intent.putExtra(IntentConsts.id, jiFenMingXiEntity.getAppId());
        intent.putExtra(IntentConsts.packageName, jiFenMingXiEntity.getPackageName());
        intent.putExtra(IntentConsts.type, type);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, String appId, String packageName, String type) {
        Intent intent = new Intent(context, DuiHuanJiBiActivity.class);
        intent.putExtra(IntentConsts.id, appId);
        intent.putExtra(IntentConsts.packageName, packageName);
        intent.putExtra(IntentConsts.type, type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    void addCurrent(String one) {
        // todo  累计 left right
        this.current += Long.parseLong(one);
    }

    void showAd() {// 展示广告
        mPresenter.getPermissions("game_ad_get", new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onStop() {

            }

            @Override
            public void onRequestSuccess(String requestData) {
//                SigmobFullUtil.getInstance().showAd(DuiHuanJiBiActivity.this, full -> {
//
//                    ShowRewardAdsUtil.getInstance().showAdSigmob(DuiHuanJiBiActivity.this, data -> {


                DialogXUtil.showLoading();

                GMFullUtil.getInstance().showAd(DuiHuanJiBiActivity.this, true, full -> {

                    ShowRewardAdsUtil.getInstance().showAdGM(DuiHuanJiBiActivity.this, transId -> {

                        if (TextUtils.isEmpty(transId)) {
                            return;
                        }

                        // 获取本次积分
                        PointUtil.getInstance().getPoints(transId, DuiHuanJiBiActivity.this, result -> {

                            MMKVUtil.getInstance().getKV().encode(MMKV_IS_UPDATE_GAME, true);

                            String one = result.getCurrentScore();
                            addCurrent(one);
//                            showPointDialog(PointsUtil.getLeft(current + ""), PointsUtil.getRight(current + ""));
                            showPointDialog(result);
                            mPresenter.updata();
                        });
                    });

                });
            }

            @Override
            public void onRequestfail(String errno, String errmsg) {

            }
        });

    }

//    void showPointDialog(String left, String right) { // 积分弹框

    void showPointDialog(ShowEcpmResult info) { // 积分弹框


        Logger.d("======showPointDialog=====showCount===now===" + showCount);
        Logger.d("======showPointDialog=====showCount===current===" + current);

        JiFenDialog dialog = new JiFenDialog(this,
                info,0,
                result -> {
                    if ("-1".equals(result)) {
                        // 直接收下

                        DialogXUtil.closeLoading();
                        resetCount();
//                        SigmobFullUtil.getInstance().showAd(this, back -> { });
                        GMFullUtil.getInstance().showAd(this, true, back -> {
                        });
                    } else {
                        // 我要翻倍 点击事件
                        showAd();
                        showCount++;
                    }
                });

        Logger.d("======showPointDialog=====showDialog======");
        dialog.show();

        if (showCount > 3) {
            resetCount();
        }

        // 插半屏广告
//        TxHalfUtil.getInstance().loadHalf(this, result -> {
//
//        });
        // 换成sigmob 插半屏
        // SigmobFullUtil.getInstance().showAd(this, result -> { });
        GMFullUtil.getInstance().showAd(this, true, result -> {
        });

// 显示刮刮乐 ggl
        //ScratchDialog.newInstance(DuiHuanJiBiActivity.this).show();
        TimerDialog.newInstance(DuiHuanJiBiActivity.this).show();
    }

    void resetCount() {// 重置计数器，当前分数和
        Logger.d("======showPointDialog=====showCount===reset===");
        showCount = 1; // 重置计数器
        current = 0;
    }

    @Override
    public int getView() {
        return R.layout.activity_duihuanjinbi;
    }


    @Override
    protected void onStart() {
        super.onStart();
        mPresenter.updata();
    }

    @Override
    public void initView() {

        riv_activity = findViewById(R.id.riv_activity);
        Glide.with(this)
                .load(BuildConfig.BASE_COM_URL_BANNER_IMG)
                .into(riv_activity);


        title_text = findViewById(R.id.title_text);
        title_back = findViewById(R.id.title_back);
        youxi_icon = findViewById(R.id.youxi_icon);
        youxi_name = findViewById(R.id.youxi_name);
        youxi_org = findViewById(R.id.youxi_org);
        youxi_shouyi_yue_num = findViewById(R.id.youxi_shouyi_yue_num);
        duihuanjilu_duihuanguize = findViewById(R.id.duihuanjilu_duihuanguize);
        duihuanjilu_duihuanguize_btn = findViewById(R.id.duihuanjilu_duihuanguize_btn);
        title_back.setOnClickListener(this);
        duihuanjilu_duihuanguize_btn.setOnClickListener(this);
        duihuanjilu_duihuanguize_btn.setEnabled(true);
        title_text.setText("提现");
        title_rl = findViewById(R.id.title_rl);
        title_rl_content = findViewById(R.id.title_rl_content);
        item_youxi = findViewById(R.id.item_youxi);
        duihuanjinbi_youxi = findViewById(R.id.duihuanjinbi_youxi);
        duihuanjinbi_leve = findViewById(R.id.duihuanjinbi_leve);
        duihuanjinbi_qianshu = findViewById(R.id.duihuanjinbi_qianshu);
        duihuanjinbi_content = findViewById(R.id.duihuanjinbi_content);
        duihuanjibi_duihuanguize_hint = findViewById(R.id.duihuanjibi_duihuanguize_hint);
        duihuanjilu_guize = findViewById(R.id.duihuanjilu_guize);

        duihuanjilu_guize.setLayoutManager(new LinearLayoutManager(this));
        duihuanjilu_guize.setAdapter(mPresenter.getBiliAdapter());

        duihuanjilu_duihuanguize.setLayoutManager(new GridLayoutManager(this, 3));
        duihuanjilu_duihuanguize.setAdapter(mPresenter.getAdapter());

        title_right = findViewById(R.id.title_right);
        duihuanjinbi_guize_rl = findViewById(R.id.duihuanjinbi_guize_rl);
        title_right.setOnClickListener(this);
        duihuanjinbi_head = findViewById(R.id.duihuanjinbi_head);
        duihuanjinbi_nickname = findViewById(R.id.duihuanjinbi_nickname);
        rl_bg=findViewById(R.id.rl_bg);
        String head = MMKVUtil.getInstance().getKV().decodeString(KEY_WX_HEADIMGURL);
        ;

        if (!TextUtils.isEmpty(head)) {
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .cacheInMemory(false)// 设置下载的图片是否缓存在内存中
                    .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
                    .build();
            ImageLoader imageLoader = ImageLoader.getInstance();
            imageLoader.init(ImageLoaderConfiguration.createDefault(this));
            imageLoader.displayImage(head, duihuanjinbi_head, options);
        }
        String nickName = MMKVUtil.getInstance().getKV().decodeString(KEY_WX_NICKNAME);
        if (!TextUtils.isEmpty(nickName)) {
            duihuanjinbi_nickname.setText(nickName);
        }
        duihuanjilu_shipin_btn = findViewById(R.id.duihuanjilu_shipin_btn);

        duihuanjilu_shipin_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toaster.show("激励视频广告");
                showAd();
            }
        });
        youxi_icon.setImageBitmap(AppUtils.getBitmap(this));

        setbg();
    }

    private void setbg() {
        ApplicationInfo appInfo = null;
        try {
            appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        if (appInfo!=null){
            String data = appInfo.metaData.getString("login_bg");
            if (!TextUtils.isEmpty(data)){
                int drawableId = getDrawableIdByName(this, data);
                if (drawableId!=0){
                    rl_bg.setBackgroundResource(drawableId);
                }
            }
        }
    }


    public int getDrawableIdByName(Context context, String name) {
        Resources resources = context.getResources();
        final int resourceId = resources.getIdentifier(name, "drawable", context.getPackageName());
        return resourceId;
    }

    @Override
    public void showData(JiFenMingXiEntity viewData) {
        //        游戏图标
        if (!TextUtils.isEmpty(viewData.getAppName())) {
            youxi_name.setText(viewData.getAppName());
        }

        if (!TextUtils.isEmpty(viewData.getTenantName())) {
            youxi_org.setText(viewData.getTenantName());
        }

//        KEY_WX_HEADIMGURL
//        youxi_shouyi_yue_num.setText((viewData.getScore()+viewData.getRefferScore())+" 积分");
        if (!TextUtils.isEmpty(viewData.getScore())) {
            youxi_shouyi_yue_num.setText((Long.parseLong(viewData.getScore()) / 10) + " 元宝");
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.title_back) {

            MMKVUtil.getInstance().getKV().encode(MMKV_IS_UPDATE_GAME, true);

            finish();
        } else if (view.getId() == R.id.duihuanjilu_duihuanguize_btn) {
            if (TextUtils.equals(BuildConfig.PAY_TYPE, Const.PAY_TYPE_HFXCX)){
                mPresenter.getOauthConfig();
            }else if (TextUtils.equals(BuildConfig.PAY_TYPE, Const.PAY_TYPE_HF)||TextUtils.equals(BuildConfig.PAY_TYPE, Const.PAY_TYPE_WX)){
                GMFullUtil.getInstance().showAd(this, false,
                        isOk -> {
                            duihuanjilu_duihuanguize_btn.setEnabled(false);
                            mPresenter.duihuan();
                        }
                );
            }

        } else if (view.getId() == R.id.title_right) {
            TiXianJiLuActivity.startActivity(this, mPresenter.getAPPId());
        }
    }

    @Override
    public void showTiXianBtnState(boolean b) {
        duihuanjilu_duihuanguize_btn.setEnabled(b);
    }

    @Override
    public void showLevel(UserEntity requestData, JiFenMingXiEntity jiFenMingXiEntity) {
        duihuanjinbi_leve.setText("当前等级： " + requestData.getLevel() + "级");
        String jife = "0";
        if (TextUtils.equals(mPresenter.getType(), StateConsts.TiXianType.ShouYi)) {
            if (jiFenMingXiEntity != null && !TextUtils.isEmpty(jiFenMingXiEntity.getScore())) {
                jife = jiFenMingXiEntity.getScore();
            }

        } else if (TextUtils.equals(mPresenter.getType(), StateConsts.TiXianType.TuiGuang)) {
            if (jiFenMingXiEntity != null && !TextUtils.isEmpty(jiFenMingXiEntity.getRefferScore())) {
                jife = jiFenMingXiEntity.getRefferScore();
            }
        }

        if (requestData != null && !TextUtils.isEmpty(requestData.getRate())) {
            double score =(Double.parseDouble(jife) * Double.parseDouble(requestData.getRate()))/100000;
            BigDecimal number=new BigDecimal(score);
            duihuanjinbi_qianshu.setText(Long.parseLong(jife) / 10 + " 元宝 = " + number.setScale(2,BigDecimal.ROUND_DOWN) + " 元");
        }
    }

    @Override
    public TextView getTiXianBtn() {
        return duihuanjilu_duihuanguize_btn;
    }

    @Override
    public void onEventReceived(MessageEvent event) {
        super.onEventReceived(event);
        if (event.getCode().equals(EVENT_TIXIAN_SHOWQUAN_OK)){
            GMFullUtil.getInstance().showAd(this, false,
                    isOk -> {
                        duihuanjilu_duihuanguize_btn.setEnabled(false);
                        mPresenter.duihuan();
                    }
            );
        }
    }
}
